﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using Smartec.Accounts.Camel.AMS.Model.Facades;

namespace Smartec.Accounts.Camel.AMS.Model.Entities.Validation
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    internal sealed class UniqueAttribute : ValidationAttribute
    {
        private const string DefaultErrorMessage = "Already exists";

        public string Entity { get; private set; }

        public string Name { get; private set; }

        public UniqueAttribute(string entity, string name)
            : base(DefaultErrorMessage)
        {
            if (string.IsNullOrEmpty(entity))
            {
                throw new ArgumentNullException("entity");
            }

            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            Entity = entity;
            Name = name;
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(ErrorMessageString);
        }

        protected override ValidationResult IsValid(object value,
                                                    ValidationContext validationContext)
        {
            if (value != null)
            {
                var idProperty = validationContext.ObjectInstance.GetType().GetProperty("ID");

                var idPropertyValue = idProperty.GetValue(validationContext.ObjectInstance, null);
                if (value.GetType().Name == "String")
                {
                    if (AMSObjectContextHelper.IsExist(Entity, Name, value.ToString(), (int?)idPropertyValue))
                    {
                        return new ValidationResult(
                            FormatErrorMessage(validationContext.DisplayName));
                    }
                }
                else
                {
                    if (AMSObjectContextHelper.IsExistNoneStringProperty(Entity, Name, value.ToString(), (int?)idPropertyValue))
                    {
                        return new ValidationResult(
                            FormatErrorMessage(validationContext.DisplayName));
                    }
                }

            }

            return ValidationResult.Success;
        }
    }
}
